#!/usr/bin/env python2
from MatchAnalysis import *
import sys, TickBasedRandom

def GetAllCombinations(inputList, groupsize):
    output = []
    indices = range(groupsize)
    while indices[0] < len(inputList) - groupsize + 1:
        output.append([inputList[a] for a in indices])
        indices[groupsize - 1] += 1
        for i in [ groupsize - a - 1 for a in range(groupsize) ]:
            if indices[i] >= len(inputList) - groupsize + i + 1:
                if i > 0:
                    indices[i - 1] += 1
                    indices[i] = indices[i - 1] + 1
                else:
                    indices[i] += 1
                for j in [a + i + 1 for a in range(groupsize - i - 1) ]:
                    indices[j] = indices[i] + j - i
    return output

def GenerateBestMatches(teams, teamsPerMatch, matchCount, origTeamList):
    if teamsPerMatch * matchCount > len(teams):
        raise ValueError("Too many matches or teams per match requested.")
    if matchCount == 1 and teamsPerMatch * matchCount == len(teams):
        return [ teams ]
    combinations = GetAllCombinations(teams, teamsPerMatch)
    analysisDictionary = { tuple(a): [ SameRegionMatchCount(a), RepeatMatchCount(a), RepeatRegionMatchCount(a, origTeamList), TickBasedRandom.GetInteger(0, sys.maxsize) ] for a in combinations }
    combinations.sort(key=lambda a: analysisDictionary[tuple(a)])
    indices = []
    for team in teams:
        combinationsForTeam = list(combinations)
        indices = list(set(indices).union({ [ i for i in range(len(combinationsForTeam)) if len(set(combinationsForTeam[i]).union({team})) == teamsPerMatch + 1][0] }))
        matches = [ combinationsForTeam[list(indices).pop()] ]
        i = 0
        while len(matches) < matchCount:
            if not any([len(a) + teamsPerMatch > len(set(a).union(set(combinationsForTeam[i]))) for a in matches]):
                matches.append(combinationsForTeam[i])
                combinationsForTeam = list(combinations)
                indices = list(set(indices).union({i}))
                i = -1
            i += 1
    return sorted(sorted(sorted(sorted([b for b in GetAllCombinations([combinations[a] for a in indices], matchCount) if len(set().union(*[set(c) for c in b])) == len(teams)], key=lambda a: TickBasedRandom.GetInteger(0, sys.maxsize)), key=lambda a: sum([analysisDictionary[tuple(b)][2] for b in a])), key=lambda a: sum([analysisDictionary[tuple(b)][1] for b in a])), key=lambda a: sum([analysisDictionary[tuple(b)][0] for b in a]))[0]
